package com.item.yxlottery.yxlottery.activity;

/*
 *------------------------------
 * @创建者      Administrator
 * @创建时间    2016/12/24 13:53
 * @文件描述    购买双色球
 *------------------------------
 */

import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.utils.ConvertUtils;
import com.blankj.utilcode.utils.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.item.yxlottery.yxlottery.R;
import com.item.yxlottery.yxlottery.adapter.BuySsqAdapter;
import com.item.yxlottery.yxlottery.base.BaseActivity;
import com.item.yxlottery.yxlottery.bean.BuySsqBean;
import com.item.yxlottery.yxlottery.callback.MyStringCallBack;
import com.item.yxlottery.yxlottery.common.Constant;
import com.item.yxlottery.yxlottery.utils.CountUtil;
import com.item.yxlottery.yxlottery.utils.RedNumberUtil;
import com.item.yxlottery.yxlottery.utils.UrlUtil;
import com.item.yxlottery.yxlottery.utils.Utils;
import com.item.yxlottery.yxlottery.views.CouponView;
import com.item.yxlottery.yxlottery.views.FullyLinearLayoutManager;
import com.item.yxlottery.yxlottery.views.NumberAddSubView;
import com.orhanobut.hawk.Hawk;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

public class BuySsqActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.bt_buyssq_one)
    Button mBtOne;

    @Bind(R.id.bt_buyssq_five)
    Button mBtFive;

    @Bind(R.id.bt_buyssq_selector)
    Button mBtSelector;

    @Bind(R.id.rv_buyssq_list)
    RecyclerView mRvList;

    @Bind(R.id.tv_buyssq_money)
    TextView mTvMoney;

    @Bind(R.id.bt_buyssq_buy)
    Button mBtBuy;

    @Bind(R.id.arl_buyssq_bottom)
    AutoRelativeLayout mArlBuyssqBottom;

    @Bind(R.id.cv_buyssq_circleline)
    CouponView mCvCircleline;

    @Bind(R.id.cb_buyssq_userstatement)
    CheckBox mCbUserstatement;

    @Bind(R.id.nasv_buyssq_times)
    NumberAddSubView mNasvTimes;

    @Bind(R.id.nasv_buyssq_stage)
    NumberAddSubView mNasvStage;

    private ArrayList<BuySsqBean> mBallList;
    private BuySsqAdapter mBuySsqAdapter;
    private long mTotalMoney = 0;//统计的多倍多期的金额
    private long mCountMoney = 0;//统计的单倍单期的金额
    private int mTimes = 1;//倍数
    private int mStage = 1;//期数
    private boolean mTimesState = false;//倍数能否继续减1,不能再继续变小金额就不会变小.
    private boolean mStageState = false;//期数能否继续减1.
    private String mNextPeriod;//期数

    @Override
    protected void setCustomActionBar(ImageButton ibActionbarLeft, TextView tvActionBarTitle, ImageButton ibActionbarRight, AutoRelativeLayout layoutActionbar) {
        ibActionbarLeft.setImageResource(R.drawable.leftarrow);
        ibActionbarLeft.setOnClickListener(this);
        ibActionbarRight.setVisibility(View.GONE);
        tvActionBarTitle.setText("双色球");
    }

    @Override
    protected View initView() {
        View view = View.inflate(this, R.layout.activity_buyssq, null);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initData() {
        //RecycleView填充数据
        Intent intent = getIntent();
        if (intent != null) {
            String red = intent.getStringExtra("red");
            String blue = intent.getStringExtra("blue");
            mNextPeriod = intent.getStringExtra("nextPeriod");
            mBallList = new ArrayList<>();
            long fristMoney = CountUtil.count(red.split(",").length, blue.split(",").length) * 2;//传递过来的一注的金额
            mBallList.add(new BuySsqBean(red, blue, fristMoney));
            setCountMoney(true, fristMoney);
        }
        mBuySsqAdapter = new BuySsqAdapter(R.layout.item_buyssq_lottery, mBallList);
        mBuySsqAdapter.setEmptyView(getLayoutInflater().inflate(R.layout.item_buyssq_empty, (ViewGroup) mRvList.getParent(), false));//自定义空布局
        mBuySsqAdapter.setHeaderFooterEmpty(true, true);
        FullyLinearLayoutManager linearLayoutManager = new FullyLinearLayoutManager(this);
        linearLayoutManager.setReverseLayout(true);//倒序
        mRvList.setNestedScrollingEnabled(false);
        mRvList.setLayoutManager(linearLayoutManager);
        mRvList.setAdapter(mBuySsqAdapter);
        //RecycleView底部圆形边线设置
        mCvCircleline.setSemicircleTop(false);//上边不显示
        mCvCircleline.setSemicircleBottom(true);//下边显示
        mCvCircleline.setSemicircleRadius(ConvertUtils.dp2px(this, 4));//半圆的半径
        mCvCircleline.setSemicircleGap(ConvertUtils.dp2px(this, 1));//半圆的间距
        mCbUserstatement.setChecked(true);
    }

    @Override
    protected void initEvent() {
        mBtOne.setOnClickListener(this);
        mBtFive.setOnClickListener(this);
        mBtSelector.setOnClickListener(this);
        mBtBuy.setOnClickListener(this);
        mBuySsqAdapter.getEmptyView().findViewById(R.id.tv_item_buyssq_emptyrandom).setOnClickListener(this);//空布局,立即机选点击事件
        mRvList.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void SimpleOnItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                setCountMoney(false, mBallList.get(position).getMoney());
                mBallList.remove(position);
                mBuySsqAdapter.notifyDataSetChanged();
            }
        });
        mCbUserstatement.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    mBtBuy.setClickable(true);
                } else {
                    mBtBuy.setClickable(false);
                }
            }
        });
        mNasvTimes.setOnButtonClickListener(new NumberAddSubView.OnButtonClickListener() {//倍数点击事件
            @Override
            public void onButtonSubClick(View v, int value) {
                if (value > 1) {
                    mTotalMoney -= (mCountMoney * mStage);
                }
                if (value == 1 && mTimesState == false) {
                    mTotalMoney -= (mCountMoney * mStage);
                    mTimesState = true;
                }
                mTimes = value;
                mTvMoney.setText(RedNumberUtil.numberWarning("投注金额 " + mTotalMoney + " 元", 0xffff0000));
            }

            @Override
            public void onButtonAddClick(View v, int value) {
                mTimes = value;
                mTimesState = false;
                mTotalMoney = (mCountMoney * mTimes * mStage);
                mTvMoney.setText(RedNumberUtil.numberWarning("投注金额 " + mTotalMoney + " 元", 0xffff0000));
            }
        });
        mNasvStage.setOnButtonClickListener(new NumberAddSubView.OnButtonClickListener() {//期数点击事件
            @Override
            public void onButtonSubClick(View v, int value) {
                if (value > 1) {
                    mTotalMoney -= (mCountMoney * mTimes);
                }
                if (value == 1 && mStageState == false) {
                    mTotalMoney -= (mCountMoney * mTimes);
                    mStageState = true;
                }
                mStage = value;
                mTvMoney.setText(RedNumberUtil.numberWarning("投注金额 " + mTotalMoney + " 元", 0xffff0000));
            }

            @Override
            public void onButtonAddClick(View v, int value) {
                mStage = value;
                mStageState = false;
                mTotalMoney = (mCountMoney * mTimes * mStage);
                mTvMoney.setText(RedNumberUtil.numberWarning("投注金额 " + mTotalMoney + " 元", 0xffff0000));
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ib_actionbar_left://返回
                finish();
                break;
            case R.id.bt_buyssq_one://随机一注
            case R.id.tv_item_buyssq_emptyrandom://立即机选
                mBallList.add(randomLottery());
                mBuySsqAdapter.notifyDataSetChanged();
                setCountMoney(true, 2);
                break;
            case R.id.bt_buyssq_five://随机五注
                for (int i = 0; i < 5; i++) {
                    mBallList.add(randomLottery());
                }
                mBuySsqAdapter.notifyDataSetChanged();
                setCountMoney(true, 10);
                break;
            case R.id.bt_buyssq_selector://手动选号
                Intent intent = new Intent(this, ShuangSeQiuActivity.class);
                intent.putExtra("jump", "jump");
                startActivityForResult(intent, 0);
                break;
            case R.id.bt_buyssq_buy://确认购买
                bet();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0 && data != null) {
            String red = data.getStringExtra("red");
            String blue = data.getStringExtra("blue");
            mNextPeriod = data.getStringExtra("nextPeriod");
            long money = CountUtil.count(red.split(",").length, blue.split(",").length) * 2;
            mBallList.add(new BuySsqBean(red, blue, money));
            mBuySsqAdapter.notifyDataSetChanged();
            setCountMoney(true, money);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /*- 设置并显示变化的总金额 -*/
    private void setCountMoney(boolean bool, long money) {
        if (bool) {//加
            mCountMoney += money;
            mTotalMoney = (mCountMoney * mTimes * mStage);
        } else {
            mCountMoney -= money;
            mTotalMoney -= (money * mTimes * mStage);
        }
        mTvMoney.setText(RedNumberUtil.numberWarning("投注金额 " + mTotalMoney + " 元", 0xffff0000));
    }

    /*- 随机一注 -*/
    private BuySsqBean randomLottery() {
        ArrayList<String> redList = new ArrayList<>();
        StringBuffer red = new StringBuffer();
        StringBuffer blue = new StringBuffer();
        Random random = new Random();
        while (redList.size() < 6) {
            int redNum = random.nextInt(33) + 1;
            if (!redList.contains(redNum + "")) {
                redList.add(redNum + "");
            }
        }
        for (String s : redList) {
            red.append(s + ",");
        }
        int blueNum = random.nextInt(16) + 1;
        if (!blue.toString().contains(blueNum + "")) {
            blue.append(blueNum + ",");
        }
        return new BuySsqBean(red.toString(), blue.toString(), 2);
    }

    /*- 下单 -*/
    private void bet() {
        String token = Hawk.get("appToken");
        String goodsid = "1";//彩种id
        String lotterPeriod = mNextPeriod;//投注期数nextPeriodqi
        String contentJson = getStringBuffer();//投注内容"01 05 13 19 20 29 30 33, 08|01 05 13 19 20 29 30 33, 08|01 05 13 19 20 29 30 33, 08";//多注
        String lotteryTimes = mTimes+"";//倍数
        String addPeriods = mStage+"";//追期数
        String play = "";//玩法
        String money = mTotalMoney+"";//金额
        String number = mTotalMoney/2+"";//注数
        String isPd = "0";//是否是余额,1是0不是
        String lotteryVo = "{"+"\"goodsId\":\""+goodsid+"\","+"\"lotterPeriod\":\""+lotterPeriod+"\","+"\"contentJson\":\""+contentJson+"\","+"\"play\":\""+play+"\","+"\"lotteryTimes\":\""+lotteryTimes
                +"\","+"\"addPeriods\":\""+addPeriods+"\","+"\"money\":\""+money+"\","+"\"number\":\""+number+"\","+"\"isPd\":\""+isPd+"\"}";

        OkHttpUtils.post().url(UrlUtil.getBetUrl()).addParams("appToken", token).addParams("lotteryVoJson", lotteryVo).build().execute(new MyStringCallBack(this, true) {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                JSONObject parse = (JSONObject) JSON.parse(response);
                Utils.log("parse----------"+parse);

                if (parse.getString("error_code").equals(Constant.SUCCESS)){
                    ToastUtils.showShortToastSafe(BuySsqActivity.this, parse.getString("msg"));
                    BuySsqActivity.this.finish();

                }else {
                    ToastUtils.showShortToastSafe(BuySsqActivity.this, parse.getString("msg"));
                }



            }
        });
    }

    private String getStringBuffer() {
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < mBallList.size(); i++) {
            String[] redBalls = mBallList.get(i).getRed().split(",");
            String[] blueBalls = mBallList.get(i).getBlue().split(",");
            ArrayList<Integer> redList = new ArrayList<>();
            ArrayList<Integer> blueList = new ArrayList<>();

            for (String red : redBalls) {
                redList.add(Integer.parseInt(red));
            }
            for (String blue : blueBalls) {
                blueList.add(Integer.parseInt(blue));
            }
            Collections.sort(redList);
            Collections.sort(blueList);

            for (int j = 0; j < redList.size(); j++) {
                if (j == redList.size() - 1) {
                    if (redList.get(j) < 10) {
                        buffer.append("0" + redList.get(j) + ",");
                    } else {
                        buffer.append(redList.get(j)).append(",");
                    }
                } else {
                    if (redList.get(j) < 10) {
                        buffer.append("0" + redList.get(j) + " ");
                    } else {
                        buffer.append(redList.get(j)).append(" ");
                    }
                }
            }

            for (int k = 0; k < blueList.size(); k++) {
                if (k == blueList.size() - 1) {
                    if (i == mBallList.size() - 1) {
                        if (blueList.get(k) < 10) {
                            buffer.append("0" + blueList.get(k));
                        } else {
                            buffer.append(blueList.get(k));
                        }
                    } else {
                        if (blueList.get(k) < 10) {
                            buffer.append("0" + blueList.get(k) + "|");
                        } else {
                            buffer.append(blueList.get(k) + "|");
                        }
                    }

                } else {
                    if (blueList.get(k) < 10) {
                        buffer.append("0" + blueList.get(k) + " ");
                    } else {
                        buffer.append(blueList.get(k) + " ");
                    }
                }
            }

        }
        return buffer.toString();

    }

}